import logging
from django.conf import settings
from django.shortcuts import render
from QQLoginTool.QQtool import OAuthQQ
from rest_framework import status

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from .serializers import QQAuthUserSerializer
from .models import OAuthQQUser
from .utils import generate_save_user_token


logger = logging.getLogger('django')


class QQAuthUserView(APIView):
    # serializer_class = '序列化器'

    def get(self, request):

        code = request.query_params.get('code')

        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )

        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)
        except Exception as error:
            logger.info(error)
            return Response({'message': 'qq服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            oauth_model = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            access_token_openid = generate_save_user_token(openid)
            return Response({'access_token': access_token_openid})
        else:
            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

            # 获取oauthModel关联/绑定的用户模型对象
            user = oauth_model.user
            payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
            token = jwt_encode_handler(payload)
            return Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })

    def post(self, request):
        """openid绑定用户"""
        # 1.创建序列化器对象
        serializer = QQAuthUserSerializer(data=request.data)
        # 2.数据校验
        serializer.is_valid(raise_exception=True)
        # 3.保存
        user = serializer.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

        payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
        token = jwt_encode_handler(payload)
        response =  Response({
            'user_id': user.id,
            'username': user.username,
            'token': token
        })

        return response


class QQAuthURLView(APIView):

    def get(self, request):
        next = request.query_params.get('next')

        if not next:
            next = '/'

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        login_url = oauth.get_qq_url()

        return Response({'login_url': login_url})
